package com.example.demo.controller;


import com.example.demo.service.DocumentGenerationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;


@RestController
@RequestMapping("/api")
public class ApiDocController {


    //private final ChatClient chatClient;
    @Autowired
    private final DocumentGenerationService docGenService;

    // 缓存生成的文档


    private static long lastGeneratedTime = 0;

    public ApiDocController(DocumentGenerationService docGenService) {
        this.docGenService = docGenService;
    }

    @PostMapping("/generate-doc")
    public ResponseEntity<ApiResponse> generateApiDoc(@RequestBody Map<String, String> request) {
        //前端输入
        String folderPath = request.get("path");
        String template = request.get("template");
            //examplePath: D:\A-Project\LLM\TalkRobot\src\main\java\com\example\talkrobot\controller
        //examplePath: D:\A-Project\LLM\autoapi-master\src\main\java\games\kibo\autoapi\controller
        //String basePath = System.getProperty("user.dir");  // 获取当前项目根目录
        //File folder = new File(basePath, "src/main/java/com/example/talkrobot/controller");

        docGenService.generateDocumentAsync(folderPath,template)
                .exceptionally(ex -> "生成失败：" + ex.getMessage())
                .thenAccept(result -> { });


        return ResponseEntity.ok(ApiResponse.success("文档生成已启动，请稍后查看结果"));
    }





    @GetMapping("/download-openapi")
    public ResponseEntity<FileSystemResource> downloadOpenApi() {
        Path path = Paths.get("src/main/resources/static/openapi.json");
        File file = path.toFile();

        if (!file.exists()) {
            throw new RuntimeException("文件不存在");
        }

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setContentDispositionFormData("attachment", "openapi.json");

        return ResponseEntity.ok()
                .headers(headers)
                .body(new FileSystemResource(file));
    }






    @GetMapping("/current-path")
    public String getCurrentPath() throws IOException {
        return new File(".").getCanonicalPath();
    }


    //提取关键信息





    // 通用响应格式
    private record ApiResponse<T>(boolean success, T data, String error) {
        static <T> ApiResponse<T> success(T data) {
            return new ApiResponse<>(true, data, null);
        }

    static ApiResponse<String> error(String message) {
        return new ApiResponse<>(false, null, message);
    }
    }


}
